import mongoose from 'mongoose'
import config from '../config'
var Schema = mongoose.Schema
  // 
mongoose.Promise = global.Promise
mongoose.connect(config.database)
var db = mongoose.connection;
db.on('error', function(err) {
  console.log(err)
})


function blogdemo() {
  var Schema = mongoose.Schema
  var blogSchema = new Schema({
    title: String,
    author: String,
    body: String,
    comments: [{ body: String, date: Date }],
    date: { type: Date, default: Date.now },
    hidden: Boolean,
    meta: {
      votes: Number,
      favs: Number
    }
  })
  var Blog = mongoose.model('blog', blogSchema)
    // 添加测试数据
  var oneBlog = new Blog({
    'title': '这是一个测111试',
    'author': '这是我',
    'hidden': false,
    'meta': {
      'votes': 324,
      favs: 231231
    }
  })
  Blog.find({ author: /这是我/ }, (err, blog) => {
    if (err) { console.log(err) }

    console.log('执行成功');
    console.log(blog.length);

  })
}


function parentDemo() {
  var Schema = mongoose.Schema

  var childType1 = new Schema({
    des: String,
    info: String
  })
  var childType2 = new Schema({
    des: String,
    info: String
  })
  var parentType = new Schema({
    des: String,
    info: String,
    children: [childType1, childType2]
  })
  var Parent = mongoose.model('Parent', parentType);
  var oneparent = new Parent({ des: '这是父元素', children: [{ name: '这是子分类1', info: "这里显示的是子分类", des: '你好啊' }, { name: '这是子分类2', info: "这里显示的是子分类2" }] })
  oneparent.save((err, ob) => {
    if (err) console.log(err)
    console.log(ob)

  })

}

const Term = new mongoose.Schema({
  _id: Number,
  terms_type: { type: String, default: 'normal' },
  terms_name: { type: String, required: true },
  terms_subtitle: { type: String },
  terms_create_time: { type: Date, default: Date.now },
  terms_enable_time: { type: Date, default: Date.now },
  terms_disable_time: { type: Date, default: Date.now },
  questions: [{ type: Schema.Types.ObjectId, ref: 'questions' }]
})

const Questions = new mongoose.Schema({
  _creator: { type: Number, ref: 'terms' },
  questions_type: { type: String, default: 'normal' },
  questions_name: { type: String, required: true },
  questoins_options: { type: Array },
  questions_true_answers: { type: Array },
  questions_create_time: { type: Date, default: Date.now }
})


const term = mongoose.model('terms', Term)
const questions = mongoose.model('questions', Questions)


const oneterm = new term({
  _id: 1,
  terms_subtitle: '新增一份试题',
  terms_name: '最新一期',
  questions: [],
})
// oneterm.save((err, term) => {
//   if (err) return err;

//   let onequestion = new questions({
//     _creator: oneterm._id,
//     questions_name: '联动添加一个答题'
//   });
//   onequestion.save((err, data) => {
//     if (err) return err;
//     console.log('同时应该插入了一条quesitons')
//   });
// })

questions.findOne({questions_name:/联动添加一个答题/}).populate('_creator').exec((err,term)=>{
    if(err)console.log(err); 

    console.log(term);
})
